﻿#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.IO;
using System.Xml;
using System.Diagnostics;
using BUS;
using DTO;
#endregion

namespace TVC.Modules.CustomControl
{

    public partial class DocumentLink : UserControl
    {
        private List<Path> mPath = new List<Path>();
        string xmlPath;
        private string _db;

        public string Db
        {
            get { return _db; }
            set { _db = value; }
        }
        private string _trans_type;
        private string _reference;
        private MainForm _mainform;
        public delegate void DocLinkHandle(object sender);
        public event DocLinkHandle ChangeEvent;
        public object _trans = null;


        public DocumentLink()
        {
            InitializeComponent();
        }
        public void loadUrl()// Load 1 lan o form cha
        {
            XmlDocument doc = new XmlDocument();
            xmlPath = MainForm.ServerPath + "Configuration\\DocumentLink.xml";
            if (File.Exists(xmlPath))
            {
                doc.Load(xmlPath);
                XmlElement root = doc.DocumentElement;

                XmlNodeList mNode = root.SelectNodes("ITEM");
                foreach (XmlElement node in mNode)
                {
                    Path path = new Path(node.GetAttribute("Url").ToString().Trim(), node.GetAttribute("View").ToString().Trim());


                    bool isroot = bool.Parse(node.GetAttribute("root"));

                    if (isroot)
                    {
                        XmlNodeList mFolder = node.SelectNodes("FOLDER");
                        path.Isroot = true;
                        foreach (XmlElement fol in mFolder)
                        {
                            Path subPath = new Path(path.Url + fol.InnerText, path.View, fol.InnerText);
                            if (Directory.Exists(subPath.Url))
                            {
                                path.MPath.Add(subPath);
                            }
                        }

                    }
                    mPath.Add(path);
                }


            }

        }
        public void Clear()
        {
            this._reference = "";
            // DoclinkBis.Clear();
            dataGridView1.Rows.Clear();
        }
        public int getLinkCount()
        {
            return dataGridView1.Rows.Count - 1;
        }
        public void Initialization(string db, string trans_type, string reference, MainForm getMainForm) // Goi khi thay doi contact
        {
            this._db = db;
            this._trans_type = trans_type;
            this._reference = reference;
            this._mainform = getMainForm;
            //       Rebind();
        }
        public string Delete(string refer)
        {
            DocLinkControl dlCtr = new DocLinkControl();
            if (_trans != null) dlCtr.SetTransaction(_trans);
            this._reference = refer;

            string sErr = dlCtr.Delete(this._db, this._trans_type, this._reference);
            dataGridView1.Rows.Clear();
            return sErr;
        }

        public string Update(string refer)
        {
            //    Rebind();
            DocLinkControl dlCtr = new DocLinkControl();
            if (_trans != null) dlCtr.SetTransaction(_trans);
            string sErr = "";
            sErr = dlCtr.Delete(this._db, this._trans_type, this._reference);
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (sErr != "") return sErr;
                if (!r.IsNewRow)
                {
                    DocLinkInfo inf = new DocLinkInfo()
                    {
                        ID = Convert.ToInt32(r.Cells["ID"].Value),
                        URL = r.Cells["URL"].Value + "",
                        DB = this._db,
                        REFERENCE = refer,
                        TRANS_TYPE = this._trans_type,
                        TITLE = r.Cells["TITLE"].Value + "",
                        CATEGORY = r.Cells["CATEGORY"].Value + ""
                    };
                    if (sErr == "" && inf.TITLE != "") dlCtr.Add(inf, ref sErr);
                }
            }

            return sErr;
        }
        public void Rebind()
        {
            string sErr = "";
            BUS.DocLinkControl ctr = new DocLinkControl();
            DataTable dt = ctr.GetAll(ref sErr, this._db, this._trans_type, this._reference);
            dataGridView1.Rows.Clear();
            //dataGridView1.DataSource = dt;

            bool isID = dataGridView1.Columns.Contains("ID"),
                isURL = dataGridView1.Columns.Contains("URL"),
                isTITLE = dataGridView1.Columns.Contains("TITLE"),
                isCATEGORY = dataGridView1.Columns.Contains("CATEGORY");
            foreach (DataRow r in dt.Rows)
            {
                int index = dataGridView1.Rows.Add();
                if (isID) dataGridView1.Rows[index].Cells["ID"].Value = r["ID"];
                if (isURL) dataGridView1.Rows[index].Cells["URL"].Value = r["URL"];
                if (isTITLE) dataGridView1.Rows[index].Cells["TITLE"].Value = r["TITLE"];
                if (isCATEGORY) dataGridView1.Rows[index].Cells["CATEGORY"].Value = r["CATEGORY"];
            }

        }
        public void SetEnabled(bool value)
        {
            EnabledFrom(value);

        }


        public void EnabledFrom(bool p)
        {
            _blReadOnly = p;
            //dataGridView1.ReadOnly = !p;
            this.dataGridView1.Columns[0].ReadOnly = !p;
            this.dataGridView1.Columns[1].ReadOnly = !p;
            this.dataGridView1.Columns[2].ReadOnly = !p;
            this.dataGridView1.Columns[3].ReadOnly = false;
            this.dataGridView1.AllowUserToAddRows = p;
            dataGridView1.Update();


        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1 && _trans_type != "" && _db != "")
            {
                //DataTable dt = DoclinkBis.DataSource as DataTable;
                if (e.ColumnIndex == 1 && _blReadOnly != false) // Click add
                {
                    //SelectFileDialog uf = new SelectFileDialog(mPath);
                    //uf.FormClosed += (form, frmArgs) =>
                    //{
                    //    if (((SelectFileDialog)form).DialogResult == DialogResult.OK)
                    //    {
                    //        if (uf.ReturnPath != null)
                    //        {
                    //            int index = e.RowIndex;

                    //            if (dataGridView1.Rows[e.RowIndex].IsNewRow) index = dataGridView1.Rows.Add();
                    //            DataGridViewRow newRow = dataGridView1.Rows[index];

                    //            newRow.Cells["URL"].Value = uf.ReturnPath;
                    //            newRow.Cells["TITLE"].Value = uf.ReturnTitle;
                    //            newRow.Cells["CATEGORY"].Value = uf.ReturnCategory;

                    //        }
                    //    }
                    //};
                    //uf.ShowDialog();
                    OpenFileDialog op = new OpenFileDialog();
                    op.MaxFileSize = 1048576;
                    op.ShowDialog();
                    op.FileOk += (form, frmArgs) =>
                    {
                        try
                        {
                            //   OpenFileDialog op = sender as OpenFileDialog;
                            Gizmox.WebGUI.Common.Resources.FileHandle objFile = null;
                            if (op.Files[0] == null || !(op.Files[0] is Gizmox.WebGUI.Common.Resources.FileHandle))
                            {
                                return;
                            }
                            objFile = op.Files[0] as Gizmox.WebGUI.Common.Resources.FileHandle;

                            String parepath = System.IO.Path.Combine(VWGContext.Current.Server.MapPath("~"), "Upload");
                            
                            string myFilePath = System.IO.Path.Combine(parepath + "\\" + _db + "\\" + _trans_type, objFile.OriginalFileName.Split('.')[0] + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + "." + objFile.OriginalFileName.Split('.')[1]);
                            parepath = System.IO.Path.GetDirectoryName(myFilePath);

                            if (!Directory.Exists(parepath))
                            {
                                Directory.CreateDirectory(parepath);

                            }

                            objFile.SaveAs(myFilePath);
                            objFile.Close();

                            int index = e.RowIndex;

                            if (dataGridView1.Rows[e.RowIndex].IsNewRow) index = dataGridView1.Rows.Add();
                            DataGridViewRow newRow = dataGridView1.Rows[index];
                            if (dataGridView1.Columns.Contains("URL")) newRow.Cells["URL"].Value = myFilePath;
                            if (dataGridView1.Columns.Contains("TITLE")) newRow.Cells["TITLE"].Value = objFile.OriginalFileName.Split('.')[0];
                            if (dataGridView1.Columns.Contains("CATEGORY")) newRow.Cells["CATEGORY"].Value = objFile.OriginalFileName.Split('.')[1];

                            //DocLinkInfo inf = new DocLinkInfo()
                            //{
                            //    //         ID = Convert.ToInt32(r.Cells["ID"].Value),
                            //    URL = dataGridView1.Rows[e.RowIndex].Cells["URL"].Value + "",
                            //    DB = this._db,
                            //    REFERENCE = _reference,
                            //    TRANS_TYPE = this._trans_type,
                            //    TITLE = dataGridView1.Rows[e.RowIndex].Cells["TITLE"].Value + "",
                            //    CATEGORY = dataGridView1.Rows[e.RowIndex].Cells["CATEGORY"].Value + ""
                            //};
                            //DocLinkControl dlCtr = new DocLinkControl();
                            //string sErr = "";
                            //dlCtr.Add(inf, ref sErr);
                            //DataTable dt = dlCtr.GetAll(ref sErr, this._db, this._trans_type, this._reference); ;
                            ////    dt.Rows.Add(new DTO.DocLinkInfo().ToDataRow(dt));
                            //dt.AcceptChanges();
                            //dataGridView1.DataSource = dt;

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message.ToString());
                        }
                    };

                }
                else if (e.ColumnIndex == 2 && _blReadOnly != false)// remove
                {
                    if (!dataGridView1.Rows[e.RowIndex].IsNewRow)
                    {
                        dataGridView1.Rows.RemoveAt(e.RowIndex);
                        //Update(_reference);
                        //Rebind();
                    }
                }
                else if (e.ColumnIndex == dataGridView1.Columns[3].Index)//download
                {
                    if (!dataGridView1.Rows[e.RowIndex].IsNewRow)
                    {
                        string fileName = dataGridView1.Rows[e.RowIndex].Cells["URL"].Value.ToString();
                        fileName = returnServerPath(fileName);

                        if (File.Exists(fileName))
                        {
                            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

                            //file.Save(ms);
                            String name = dataGridView1.Rows[e.RowIndex].Cells["TITLE"].Value.ToString() + "." + dataGridView1.Rows[e.RowIndex].Cells["CATEGORY"].Value.ToString();
                            //DownloadGateway myDownload = new DownloadGateway(fs, name);
                            ////myDownload.DownloadAsAttachment = false;
                            //myDownload.StartDownload(this);

                            FileDownloadGateway downloadGateway = new FileDownloadGateway();
                            downloadGateway.Filename = name;
                            //      downloadGateway.ver = file.Version;
                            downloadGateway.SetContentType(DownloadContentType.OctetStream);
                            byte[] buff = null;
                            BinaryReader br = new BinaryReader(fs);
                            long numBytes = new FileInfo(fileName).Length;
                            buff = br.ReadBytes((int)numBytes);

                            downloadGateway.StartBytesDownload(new ContainerControl(), buff);

                            //DownloadGateway download = new DownloadGateway();
                            //FileInfo fileObj = new FileInfo(fileName);
                            //download.
                            //download.Filename = fileObj.Name;
                            //download.StartFileDownload(this, fileName);
                        }
                        else
                        {
                            MessageBox.Show("File does not exist or is unreadable!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                        }
                    }
                }


            }


        }

        void op_FileOk(object sender, CancelEventArgs e)
        {

        }
        public string returnServerPath(string filename)
        {
            foreach (Path path in mPath)
            {
                if (filename.IndexOf(path.View) >= 0)
                {
                    return path.ConvertToServerPath(filename);
                }
            }

            return filename;
        }

        public void Copy(string refer)
        {
            this._reference = refer;
        }
        public void reLoad(string refer)
        {
            this._reference = refer;
            Rebind();
        }

        private void dataGridView1_NewRowNeeded(object sender, DataGridViewRowEventArgs e)
        {
            //       InitNewRow(e.Row);
        }

        public bool _blReadOnly { get; set; }

        private void dataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {

        }
    }


    public partial class EditDialog : Form
    {
        public string name;
        public EditDialog()
        {
            InitializeComponent();
        }
        public EditDialog(string title)
        {
            InitializeComponent();
            this.Text = title;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                this.DialogResult = DialogResult.OK;
                this.name = textBox1.Text.Trim();
                this.Close();
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
    public class Path
    {
        private string url;
        private string view;
        private bool isroot = false;
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public bool Isroot
        {
            get { return isroot; }
            set { isroot = value; }
        }

        private List<Path> mPath = new List<Path>();

        public List<Path> MPath
        {
            get { return mPath; }
            set { mPath = value; }
        }



        public Path(string url, string view)
        {
            this.url = url;
            this.view = view;
        }
        public Path(string url, string view, string name)
        {
            this.url = url;
            this.view = view;
            this.name = name;
        }

        public string Url
        {
            get { return url; }
            set { url = value; }
        }


        public string View
        {
            get { return view; }
            set { view = value; }
        }

        public string ConvertToVitualPath(string url)
        {
            string output = url.Replace(this.url, this.view);
            return output;
        }

        public string ConvertToServerPath(string url)
        {
            string output = url.Replace(this.view, this.url);
            return output;
        }
    }

}